package com.bjpower.services.impl;
import java.util.Date;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.bjpower.common.enums.PublicStatus;
import com.bjpower.common.enums.SysCode;
import com.bjpower.common.exceptions.type.SysException;
import com.bjpower.common.mail.MailProperty;
import com.bjpower.domain.UserInfo;
import com.bjpower.domain.UserPayConfig;
import com.bjpower.domain.UserPayInfo;
import com.bjpower.mapper.UserInfoMapper;
import com.bjpower.mapper.UserPayConfigMapper;
import com.bjpower.mapper.UserPayInfoMapper;
import com.bjpower.models.dto.MailDto;
import com.bjpower.models.request.CreatePayWayConfigRequest;
import com.bjpower.models.request.UserPageInfoRequest;
import com.bjpower.services.PayConfigListService;
import com.bjpower.utlis.MailUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class PayConfigListServiceImpl implements PayConfigListService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private UserPayConfigMapper userPayConfigMapper;

    @Resource
    private UserPayInfoMapper userPayInfoMapper;

    @Resource
    private UserPayConfigMapper payConfigMapper;

    @Resource
    private MailUtil mailUtil;

    @Override
    public IPage<UserPayConfig> getPayConfigList(UserPageInfoRequest pageInfoRequest) {
        QueryWrapper<UserPayConfig> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("edit_time");
        IPage<UserPayConfig> payProductIPage = userPayConfigMapper.selectPage(
                Page.of(pageInfoRequest.getPageNum(), pageInfoRequest.getPageSize()), wrapper);
        return payProductIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createPayConfig(CreatePayWayConfigRequest configRequest) {
        StringBuffer buffer = new StringBuffer();
        //商户支付产品和用户只能绑定一个
        QueryWrapper<UserPayInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_no", configRequest.getUserNo())
                .eq("product_code", configRequest.getProductCode());
        Long count = userPayInfoMapper.selectCount(wrapper);
        if (count > 0) {
            throw new SysException(SysCode.MERCH_PAY_CONFIG_EXIST);
        }


        //创建user_pay_config表
        UserPayConfig userPayConfig = new UserPayConfig();
        userPayConfig.setId(IdWorker.get32UUID());
        userPayConfig.setUserNo(configRequest.getUserNo());
        userPayConfig.setShopName(configRequest.getShopName());
        userPayConfig.setProductCode(configRequest.getProductCode());
        userPayConfig.setProductName(configRequest.getProductName());
        userPayConfig.setRiskDay(configRequest.getRiskDay());
        userPayConfig.setAppKey(IdWorker.get32UUID());
        userPayConfig.setAppSecret(IdWorker.get32UUID()); //做签名的秘钥
        userPayConfig.setMerchantServerIp(configRequest.getIpList());
        userPayConfig.setAutoSett("autoYes".equals(configRequest.getAutoSett()) ? "YES" : "NO");
        userPayConfig.setRemark("创建商户配置支付产品");
        userPayConfig.setEditTime(new Date());
        userPayConfig.setStatus(PublicStatus.ENABLE.name());
        payConfigMapper.insert(userPayConfig);


        buffer.append("支付方式：");
        //创建user_pay_info表
        if (configRequest.getKqConfig() != null) {
            UserPayInfo userPayInfo = new UserPayInfo();
            userPayInfo.setId(IdWorker.get32UUID());
            userPayInfo.setProductCode(configRequest.getProductCode());
            userPayInfo.setUserNo(configRequest.getUserNo());
            userPayInfo.setShopName(configRequest.getShopName());
            userPayInfo.setPayWayCode("KUAIQIAN");
            userPayInfo.setPayWayName("快钱支付");
            userPayInfo.setPayConfig(JSONUtil.toJsonStr(configRequest.getKqConfig()));
            userPayInfo.setRemark("创建快钱第三方支付参数");
            userPayInfo.setEditTime(new Date());
            userPayInfo.setStatus(PublicStatus.ENABLE.name());
            userPayInfoMapper.insert(userPayInfo);
            buffer.append("KUAIQIAN").append(";");
        }
        if (configRequest.getWxConfig() != null){
            UserPayInfo userPayInfo = new UserPayInfo();
            userPayInfo.setId(IdWorker.get32UUID());
            userPayInfo.setProductCode(configRequest.getProductCode());
            userPayInfo.setUserNo(configRequest.getUserNo());
            userPayInfo.setShopName(configRequest.getShopName());
            userPayInfo.setPayWayCode("WEIXIN");
            userPayInfo.setPayWayName("微信支付");
            userPayInfo.setPayConfig(JSONUtil.toJsonStr(configRequest.getWxConfig()));
            userPayInfo.setRemark("创建快钱第三方支付参数");
             userPayInfo.setEditTime(new Date());
            userPayInfo.setStatus(PublicStatus.ENABLE.name());
            userPayInfoMapper.insert(userPayInfo);
            buffer.append("WEIXIN").append(";");
        }
        buffer.append("商户号：").append(configRequest.getUserNo()).append(";")
                .append("支付产品代码：").append(configRequest.getProductCode()).append(";")
                .append("支付产品名称：").append(configRequest.getProductName()).append(";")
                .append("appKey：").append(userPayConfig.getAppKey()).append(";")
                .append("appSecret：").append(userPayConfig.getAppSecret());
        MailDto mailDto = new MailDto();
        QueryWrapper<UserInfo>  queryWrapper  = new QueryWrapper<>();
        queryWrapper.select("user_email").eq("user_no",configRequest.getUserNo());
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        //此处为测试，实际开发中需要根据商户信息查询出邮箱放入此里
        String userEmail = userInfo.getUserEmail();
        mailDto.setUserMail("");
        mailDto.setSubject("商户支付配置");
        mailDto.setText(buffer.toString());

        //发送邮件
        new Thread(() -> {
            sendFile(mailDto);
        }).start();
    }
    //发送文件的方法
    public void sendFile(MailDto mailDto) {
        MailProperty mailProperty = new MailProperty();
        mailProperty.setFrom("W13466916748@163.com");
        mailProperty.setTo(new String[]{"1521664522@qq.com"});
        mailProperty.setSubject("测试邮件");
        mailProperty.setContent("测试邮件内容");
        mailUtil.sendSimpleMail(mailProperty);
    }

}
